package a17_Reflection.Test.Constructor;

import java.lang.reflect.Field;

/**
 * @Author quan
 * @Description Class类获取成员变量
 * @Date 2023/5/1 16:20
 */
public class MyReflect2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        //1、获取class字节码文件
        Class cls = Class.forName("a17_Reflection.Test.Constructor.Student2");
        //2、获取成员变量
        //(1)获取所有公共的
        Field[] fields = cls.getFields();
        for (Field field: fields) {
            System.out.println(field);
        }
        //(2)获取所有的包括私有的
        Field[] fields1 = cls.getDeclaredFields();
        for (Field field: fields1) {
            System.out.println(field);
        }
        //(3)获取单个的gender
        Field gender = cls.getField("gender");
        System.out.println(gender);
        //name私有的
        Field name = cls.getDeclaredField("name");
        System.out.println(name);
        //获取权限修饰符
        int modifiers = name.getModifiers();
        System.out.println(modifiers);
        //获取成员变量的名字
        String n = name.getName();
        System.out.println(n);
        //获取成员变量的数据类型
        Class<?> type = name.getType();
        System.out.println(type);
        //获取成员变量记录的值
        name.setAccessible(true);
        Student2 s = new Student2("张三",23,"男");
        String value = (String) name.get(s);
        System.out.println(value);
    }
}
